#!/bin/bash
#information
#author: gr.cn 
#email: 920098699@qq.com
#date: Mon Jun  3 20:21:48 CST 2013
#function:　删除用户，步骤如下：
#1.获得要删除用户账户的正确账户名
#2.强制终止正在运行属于该用户的进程
#3.确认系统属于该账户的所有文件
#4.删除用户

#获取应删除的用户
get_answer(){
	ASK_COUNT=1
	unset ANSWER
	while [ -z "$ANSWER" ]
	do
		case $ASK_COUNT in
		1)
			echo "the first time to read"
			;;
		2)
			echo "the sencond time to read"
			;;
		3)
			echo "the last time to read"
			;;
		4)
			echo "error input over 3 times"
			echo "the script going to exit..."
			exit 1
			;;
		esac
	
		ASK_COUNT=$[ $ASK_COUNT + 1]
		if [ -n "$LINE2" ]
		then
			echo $LINE1
			echo -e $LINE2" \c"
		else
			echo -e $LINE" \c"
		fi
		read -t 60 ANSWER 
	done 
	unset LINE1
	unset LINE2
}

#判断用户是否存在
is_exist_user(){
	USER_ACCOUNT_RECORD=$(cat /etc/passwd | grep -w $USER_ACCOUNT)
	if [ $? -eq 1 ]
	then
		echo "the account '$USER_ACCOUNT' does not exist"
		echo "the script going to exit..."
		exit 1
	fi
	echo "find the user '$USER_ACCOUNT_RECORD'"
}

#确认是否删除
process_answer(){
	case $ANSWER in
	y|Y|YES|YEs|YeS|Yes|yES|yEs|yeS|yes)
	
	;;
	*)
			echo $EXIT_LINE1
			echo $EXIT_LINE2
			exit 1
	;;
	esac
	unset EXIT_LINE1
	unset EXIT_LINE2
}
process_process(){
	ps -u $USER_ACCOUNT
	case $? in
	1)
		echo "There are no process of the user $USER_ACCOUNT"
		echo
	;;
	0)
		echo
		unset ANSWER
		LINE1="Would you like to kill the process(es)?[y/N]"
		get_answer
		process_answer
		trap "rm $USER_ACCOUNT_Running_Process.rpt" SIGTERM SIGINT SIGQUIT
		ps -u $USER_ACCOUNT > $USER_ACCOUNT_Running_Process.rpt
		exec < $USER_ACCOUNT_Running_Process.rpt 
		read USER_PROCESS_REC
		read USER_PROCESS_REC
		while [ $? -eq 0　]
		do
			USER_PID=$(echo $USER_PROCESS_REC | awk '{print $1}')
			kill -9 $USER_ID
			echo "killed the process $USER_ID"
			read USER_PROCESS_REC
		done
		rm $USER_ACCOUNT_Running_Process.rpt 
	;;
	*)
		echo
		echo "Will not kill the process"
		echo
	;;
	esac
}

file_report(){
	echo
	echo "Step #3-Find all the files of the user $USER_ACCOUNT"
	echo
	DATE=`date +%Y-%m-%d_%H:%M:%S`
	FILE=/home/gr/archive/user_file/$DATE
	find / -user $USER_ACCOUNT > $FILE 2> /dev/null
	echo "Report is completed"
	echo "Name of report: $FILE"
	echo
}

delete_user(){
	LINE1="do you want to delete the user $USER_ACCOUNT"
	get_answer
	EXIT_LINE1="since you don't want to delete the user"
	EXIT_LINE2="we will exit the script..."
	process_answer
	
	userdel $USER_ACCOUNT
}

#1　确定要删除的用户
LINE1="Please input the name of the user"
LINE2="the account you want to delete from the system:"
get_answer
USER_ACCOUNT=$ANSWER

is_exist_user
LINE1="Is '$USER_ACCOUNT_RECORD is the account"
LINE2="you wish ot delete?[y/N]"
get_answer
EXIT_LINE1="Because '$USER_ACCOUNT' is not the account"
EXIT_LINE2="you want to delete. we are leaving the script..."
process_answer
#2  属于用户的线程
process_process

#3  创建用户的文件报告
file_report

#4  删除用户
delete_user
